/*
 * shaders.cpp
 *
 *  Created on: 26.04.2013
 *      Author: SomeChineseGuy
 */

#include "shaders.h"

#include <string>
#include <iostream>
#include <fstream>

#define GL_GLEXT_PROTOTYPES
#include <GL3/gl3w.h>


string readShadertoString(const char* filename) {

	ifstream file;
	file.open(filename, ios::in);

	string shaderStr;
	shaderStr.assign(istreambuf_iterator<char>(file),
			istreambuf_iterator<char>());

	file.close();

	return shaderStr;

}

GLuint createShader(GLenum type, string sourceCode, string fName) {

	GLuint shaderHandle = glCreateShader(type);

	const char* charData = sourceCode.c_str();
	glShaderSource(shaderHandle, 1, &charData, NULL);

	glCompileShader(shaderHandle);
	GLint status;
	glGetShaderiv(shaderHandle, GL_COMPILE_STATUS, &status);
	if (status == GL_FALSE) {
		GLint len;
		glGetShaderiv(shaderHandle, GL_INFO_LOG_LENGTH, &len);
		char* logMessage = new char[len + 1];
		glGetShaderInfoLog(shaderHandle, len, NULL, logMessage);
		cout << "Shader compilation error:" << endl;
		cout << "\t[" << fName << "]: " << logMessage << endl;
		delete[] logMessage;
	}

	return shaderHandle;

}


GLuint createShaderProgram(vector<GLuint> shaders) {

	GLuint program = glCreateProgram();
	for (unsigned short i = 0; i < shaders.size(); i++) {
		glAttachShader(program, shaders[i]);
	}

	glLinkProgram(program);
	GLint status;
	glGetProgramiv(program, GL_COMPILE_STATUS, &status);
	if (status == GL_FALSE) {
		GLint len;
		glGetProgramiv(program, GL_INFO_LOG_LENGTH, &len);
		char* logMessage = new char[len + 1];
		glGetProgramInfoLog(program, len, NULL, logMessage);
		cout << "Shader link error:" << endl;
		cout << logMessage << endl;
		delete[] logMessage;
	}

	return program;

}
